<?php


namespace app\admin\controller;

use app\common\model\Config as C;
use app\common\model\AuthGroup;
use app\common\model\Admins;
use think\captcha\facade\Captcha;
use think\facade\Db;
use think\Exception;
use think\facade\View;
use think\facade\Request;
use think\facade\Session;
use com\Encryption;

class Login
{
    public function index()
    {
        if (session('uid') > 0) {
            redirect('Index/index');
        } else {
            if (config('site.SHOW_VERIFY') == 1) {
                View::assign('show_verify', 1);
            } else {
                View::assign('show_verify', 0);
            }

        }
        return View::fetch();
    }

    public function verify()
    {
        return Captcha::create();
    }
    public function login(){
        $username = Request::param('username', '', 'com\Encryption::filterWords');
        $password = Request::param('password', '', 'com\Encryption::filterWords');
        $captcha = Request::param('captcha', '', 'com\Encryption::filterWords');
        //print_r($captcha);die;
        if(empty($captcha) && Config('site.SHOW_VERIFY') == 1){
            return error('参数不正确');
        }
        if (empty($username) || empty($password)) {
            return error('参数不正确1');
        }
        //验证验证码填写是否正确

        if (config('site.SHOW_VERIFY') == 1) {
            if (!captcha_check($captcha)) {
                return error('验证码错误！');
            }
        }

        $request = Db::name('admins')
                ->alias('a')
                ->where('username', $username)
                ->join('auth_group_access aga','a.admin_id = aga.uid')
                ->leftJoin('auth_group ag', 'aga.group_id = ag.id')
                ->field('a.*,aga.uid,aga.group_id,ag.id,ag.title,ag.status,ag.rules')
                ->find();
        if (!empty($request) && $request['password'] == get_password($password, $request['encrypt'])) {
            Session::set('admin', $request);
            Session::set('admin.group_id' , $request['group_id']);
            Session::set('admin.rules'    , explode(',', $request['rules']));
            Session::set('admin.title'    , $request['title']);
            return success('登录成功！', url('Index/index'));
        }else{
            return error('账号或者密码错误');
        }
    }



}